<template>
    <div class="permission-management">
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入角色名称"
          clearable
          style="width:200px"
        ></el-input>
        <el-button style="margin-left: 20px" @click="search">搜索</el-button>
      </div>
      <div class="create-role-button">
        <el-button type="primary" @click="showCreateRoleDialog">创建角色</el-button>
      </div>
      <div class="role-table">
        <el-table :data="roles" border stripe>
          <el-table-column prop="id" label="ID"></el-table-column>
          <el-table-column prop="roleName" label="角色名称"></el-table-column>
          <el-table-column prop="cid" label="公司ID"></el-table-column>
          <el-table-column prop="roleComent" label="角色内容"></el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="editPermission(row)">修改权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog
        :title="isRevise===true?'修改角色':'创建角色'"
          v-model="createRoleDialogVisible"
        width="30%"
        :closeOnClickModal="false"
        :show-close="false"
      >
        <el-form v-model="createForm" >
          <el-form-item label="角色名称" >
            <el-select v-model="createForm.roleName" placeholder="请选择" :disabled="isRevise===true">
              <el-option
                  v-for="item in roleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色内容" >
            <el-input v-model="createForm.roleContent"></el-input>
          </el-form-item>
          <el-form-item label="公司名称">
            <el-select v-model="createForm.companyId" placeholder="请选择" :disabled="isRevise===true">
              <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-tree
            class="tree"
            ref="treeRef"
            :data="NewAuthority"
            show-checkbox
            node-key="id"
            :props="defaultProps"
            @check="handleCheckChange"
            :default-checked-keys="checkedKey"
        />
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancelCreateRole">取消</el-button>
            <el-button type="primary" @click="createRole">{{isRevise===true?'修改':'创建'}}</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import {onMounted, reactive, ref} from 'vue';
  import API from '@/api/manage'
  import {ElMessage} from "element-plus";
    let isRevise=ref(false)
    let checkedKey=reactive([])
    let options=reactive([])
    let roleOptions=reactive([
      {
        value: '管理员',
        label: '管理员'
      },
      {
        value: '培训师',
        label: '培训师'
      }
    ])
      let searchKeyword = ref()
      let roles = ref([{
        id:'1'
      }]);
      const createRoleDialogVisible = ref(false);
      let createForm = reactive({
        roleName: '',
        companyId: '',
        roleContent:''
      });
      const param=reactive({})
  let NewAuthority = reactive([])
  onMounted(()=>{
    queryAuth()
    queryUserRole()
    queryCompany()
  })

  const search=()=>{
    let token=localStorage.getItem('token')
    API.queryUserRole({
      roleName:searchKeyword.value.trim()
    },token).then(res=>{
      if(res.data.success===true){
        roles.value =res.data.content.records
      }
    }).catch(err=>{
      console.log(err)
    })

  }
  //根据value在数组中找值
  function findLabelByValue(value) {
    const foundObject = options.find(obj => obj.value === value);
    return foundObject ? foundObject.label : null;
  }

  //访问权限列表
      const queryAuth = ()=>{
        let token = localStorage.getItem('token')
        API.queryAuth(param,token).then((res)=>{
          console.log(res.data.content.records,'rs')
          NewAuthority=setTreeData(res.data.content.records)
        }).catch(e=>{
          console.log(e)
        })
      }
      // 访问公司列表
  const queryCompany=()=>{
        let token=localStorage.getItem('token')
        API.queryCompany({},token).then(res=>{
          options=res.data.content.records.map(item=>{
            return{
              value:item.id,
              label:item.name
            }
          })
        }).catch(err=>{
          console.log(err)
        })
  }

      const init = ()=>{
        createForm = reactive({
          roleName: '',
          companyId: '',
          roleContent:''
        })
        treeRef.value.setCheckedKeys([])
      }
      //转换后端数据格式为树形结构
      function setTreeData(arr){
        arr.forEach(function (item){
          delete item.children;
        });
        let map={};
        arr.forEach(i=>{
          map[i.id]=i;
        });
        let treeData=[];
        arr.forEach(child=>{
          const mapItem=map[child.parentId];
          if(mapItem){
            (mapItem.children||(mapItem.children=[])).push(child);
          }else{
            treeData.push(child);
          }
        });
        return treeData;
      }
      const showCreateRoleDialog = () => {
        isRevise.value=false
        createRoleDialogVisible.value = true;
      };
  
      const cancelCreateRole = () => {
        createRoleDialogVisible.value = false;
        init()

      };
      const roleParam=reactive({})

  // 创建角色or修改角色
      const createRole = () => {
        roleParam.roleName=findLabelByValue(createForm.companyId)+createForm.roleName
        roleParam.cId=createForm.companyId
        roleParam.roleComent=createForm.roleContent
        roleParam.rolePermissionList=[]
        console.log(createForm,'createForm')
        chooseNodes.forEach(item=>{
          roleParam.rolePermissionList.push({
            "permissionComent":item.frontName,
            "fId":item.id
          })
        })
        // 发送请求，保存角色数据等
        let token =localStorage.getItem('token')
        if(isRevise.value===true){
          roleParam.id=createForm.id
          API.updateUserRole(roleParam,token).then(res=>{
            console.log(res,'update')
            if(res.data.success===true){
              ElMessage.success('修改成功！')
              queryUserRole()
            }
          }).catch(err=>{
            console.log(err)
          })
        }
        else{
          API.createRole(roleParam,token).then((res)=>{
            if(res.data.code==='0'){
              ElMessage.success('创建成功！')
              queryUserRole()
            }
          }).catch(error=>{
            console.log(error)
          })
        }

        // 创建成功后关闭对话框
        createRoleDialogVisible.value = false;
        init()
      };

      const queryUserRole =  () =>{
        let token = localStorage.getItem('token')
         API.queryUserRole(param,token).then((res)=>{
           if(res.data.success===true){
             roles.value =res.data.content.records
           }
        }).catch(error=>{
          console.log(error)
        })
      }

      // 修改权限
      const editPermission = (role) => {
        createForm.roleContent=role.roleComent
        createForm.roleName=role.roleName.indexOf("管理员")!==-1?'管理员':'培训师'
        createForm.companyId=role.cid
        createForm.id=role.id
        isRevise.value=true
        let token=localStorage.getItem('token')
        API.queryRoleAuth({
          roleId:role.id
        },token).then(res=>{
          let tmpArr=res.data.content.records
          checkedKey=reactive([])
          chooseNodes=reactive([])
          tmpArr.forEach(item=>{
            checkedKey.push(item.fId)
            chooseNodes.push({
              frontName:item.permissionComent,
              id:item.fId
            })
          })
          createRoleDialogVisible.value=true
        }).catch(err=>{
          console.log(err)
        })
      };

      const defaultProps = reactive({
        children: 'children',
        label: 'frontName',
        })

    const treeRef = ref([])
    let chooseNodes = reactive([])

  //选中权限树的节点
    const handleCheckChange =(_,selectObj)=> {
       chooseNodes = selectObj.checkedNodes
    }
  </script>
  
  <style scoped>
  .tree {
    flex: 1;
    overflow: auto;
    font-size:20px;
    ::v-deep .el-tree {
      background: #1c1c1a;
      color: #d5bd87;
    }
  }

  .permission-management {
    padding: 20px;
  }
  
  .search-bar {
    margin-bottom: 20px;
    display: flex;
  }
  
  .create-role-button {
    margin-bottom: 20px;
  }
  </style>
  